import { Component, OnInit } from '@angular/core';
import {FormBuilder, FormGroup, Validators} from "@angular/forms";
import {ActivatedRoute, Router} from "@angular/router";
import {PageSubject} from "../../../../../util/page-subject";
import {OneDialogService} from "../../../../../widgets/one-dialog/one-dialog.service";
import {ResponseUtil} from "../../../../../util/response-util";
import {Path} from "../../../../../portal/admin/admin-breadcrumb/breadcrumb";
import {TplManage} from "../tpl-manage";
import {TplManageService} from "../tpl-manage.service";
import {MsgConstants} from "../../../../../constants/constants";
import {MsgResult} from "../../../../../models/msg-result";
import {DataDictionaryService} from "../../../../../services/dataDictionary.service";
import {FormUtil} from "../../../../../util/form-util";

@Component({
  selector: 'app-tpl-template-add',
  templateUrl: './tpl-template-add.component.html',
  styleUrls: ['./tpl-template-add.component.css']
})
export class TplTemplateAddComponent implements OnInit {

  // 模板对象
  template:TplManage;

  applicationTypeArr : Array<string> =[];

  tplTemplateForm: FormGroup;

  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private fb: FormBuilder,
    private formUtil: FormUtil,
    private pageSubject: PageSubject,
    private responseUtil: ResponseUtil,
    private dialogService: OneDialogService,
    private tplManageService: TplManageService,
    private dataDictionaryService: DataDictionaryService,
  ) {
    this.initTemplateObj();
  }

  ngOnInit() {
    this.pushPage();
    this.findApplicationType();
  }

  /**
   * 面包屑导航
   */
  pushPage() {
    let path = new Path("模板管理", "");
    this.pageSubject.pushPage("模板管理", "添加", path);
  }


  /**
   * 根据数据字典查询应用类型
   */
  private findApplicationType(){
    this.dataDictionaryService.getChildDicByCode('MBBGGL').subscribe(
      result => this.responseUtil.success(result ,this.processDictionaryResult),
      message => this.responseUtil.error(message)
    )
  }

  /**
   * 处理查询结果
   * @param result
   */
  private processDictionaryResult =(result :MsgResult)=>{
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.applicationTypeArr = this.formUtil.filterDictionaryByCode('MBBGGL_YYLX',result.data);
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }


  /**
   * 构造表单
   */
  buildForm(): void {
    this.tplTemplateForm = this.fb.group({
      // 'roleId': [this.role.roleId],
      'name': [this.template.name, [
        Validators.required,
        Validators.maxLength(30),
        Validators.pattern(/^(?!_)(?!.*?_$)[(a-zA-Z0-9_\-)\u4e00-\u9fa5]+$/)
      ]],
      'useType': [this.template.useType = 'daily', [
        Validators.required,
        Validators.maxLength(30),
        Validators.pattern(/^[a-zA-Z0-9_]+$/)
      ]],
      'remark': [this.template.remark, [
        Validators.maxLength(15),
        // Validators.pattern(/^(a-zA-Z0-9_)+$/)
      ]],
      'type': [this.template.type = '0', [
        Validators.maxLength(1),
      ]],
      'isUse': [this.template.isUse = '0', [
        Validators.maxLength(1),
      ]],
      'assembly': [this.template.assembly, [
        Validators.required,
        Validators.maxLength(2500),
      ]],
      'description': [this.template.description, [
        Validators.maxLength(50),
      ]]
    });

    this.tplTemplateForm.valueChanges.subscribe(
      data => this.onValueChanged(data)
    );
    this.onValueChanged();
  }


  /**
   * 值变化监听
   * @param data
   */
  onValueChanged(data?: any) {
    if (!this.tplTemplateForm) {
      return;
    }
    const form = this.tplTemplateForm;
    for (const field in this.formErrors) {
      this.formErrors[field] = '';
      const control = form.get(field);
      if (control && control.dirty && !control.valid) {
        const messages = this.validationMessages[field];
        for (const key in control.errors) {
          this.formErrors[field] += messages[key] + ' ';
        }
      }
    }
  }

  /**
   * 校验字段
   * @type {{name: string; code: string}}
   */
  formErrors = {
    'name': '',
    'useType':'',
    'remark':'',
    'assembly': '',
    'description': '',
  };

  /**
   * 校验提示信息
   * @type {{name: {required: string; maxlength: string}; code: {required: string; maxlength: string; pattern: string}}}
   */
  validationMessages = {
    'name': {
      'required': '模板名不能为空',
      'maxlength': '长度不能超过30',
      'pattern': '只能由汉字或字母、数字、下划线、中划线组成，不能以下划线开头或结尾'
    },
    'useType': {
      'required': '应用类型不能为空',
      'maxlength': '长度不能超过30',
      'pattern': '可以由字母、数字、下划线组成！'
    },
    'remark': {
      'maxlength': '长度不能超过15',
    },
    'assembly': {
      'required': '模板组件不能为空',
      'maxlength': '长度不能超过2500'
    },
    'description': {
      'maxlength': '长度不能超过50'
    }
  };



  initTemplateObj(){
    this.template = new TplManage;
    this.buildForm();
  }


  onSubmit(){
    this.template = this.tplTemplateForm.value;
    this.tplManageService.templateAdd(this.template).subscribe(
        result => this.responseUtil.success(result,this.processTemplateAdd),
        error => this.responseUtil.error(error)
    );
  }

  /**
   *
   * @param {MsgResult} result
   */
  private processTemplateAdd =(result:MsgResult) =>{
    if(result && result.code == MsgConstants.MSG_CODE_OK){
      this.dialogService.successWithCancelBtn("添加成功，是否继续添加？",()=>this.initTemplateObj(),()=>this.cancel());
    }
    if(result && result.code != MsgConstants.MSG_CODE_OK){
      this.dialogService.info(result.message);
    }
  }

  /**
   * 取消按钮
   */
  cancel(){
    this.router.navigate(['..'],{relativeTo:this.route});
  }

}
